<template>
  <div
    class="d-flex-c flex-1 overflow-hidden"
  >
    <div class="d-flex ai-c m-b-mini">
      <el-checkbox
        v-model="showText"
        true-label="1"
        false-label="0"
        size="mini"
        style="margin-right: 10px;"
        @change="changeTextOption()"
      >
        显示地图元素名称
      </el-checkbox>
      <span
        class="f-14"
        style="color: #6a6b7f;"
      >文字颜色：</span>
      <el-color-picker
        v-model="textColor"
        size="mini"
        class="m-r-mini"
        @change="changeTextOption()"
      />
      <span
        class="f-14"
        style="color: #6a6b7f;"
      >字号大小：</span>
      <BKSelect
        size="mini"
        v-model="textFontSize"
        :mock="sizesList"
        :clearable="false"
        style="width: 75px;margin-right: 10px;"
        @change="changeTextOption()"
      />
    </div>
    <div class="d-flex m-b-mini">
      <el-cascader
        v-model="currentCity"
        :options="cityData"
        size="small"
        class="m-r-mini"
        :props="{ checkStrictly: true, multiple: true }"
        clearable
      />
      <BKSelect
        v-model="selectValue"
        size="small"
        class="m-r-mini"
        style="width: 150px;"
        placeholder="请选择水库类型"
        v-if="type === '水库' || metaSet === 'ATT_RES_BASE'"
        dictionary-key="SKLX"
        clearable
      />
      <BKInput
        v-model="keywords"
        size="small"
        class="m-r-mini"
        style="width: 200px;"
        :placeholder="placeholder"
        clearable
      />
      <el-button
        size="small"
        type="primary"
        @click="search()"
      >
        搜索
      </el-button>
    </div>
    <div class="flex-1 overflow-hidden p-b-mini">
      <div class="transfer-container full-box d-flex">
        <div class="left-table flex-1 overflow-hidden d-flex-c">
          <div class="title flex-between p-h-mini b-b">
            <span class="d-flex ai-c">
              <i class="ri-list-check" />{{ titles[0] }}<span class="count m-l-mini">({{ leftTotal }})</span>
              <el-tooltip
                placement="top"
              >
                <i
                  class="el-icon-warning-outline m-l-mini c-pointer"
                  style="color: #333;font-size: 16px;"
                />
                <div slot="content">
                  文字说明<br>
                  <span class="c-red">红色文字</span> -- 该数据没有空间矢量信息
                </div>
              </el-tooltip>
            </span>
            <el-button
              type="text"
              style="font-size: 16px;"
              @click="alllLeftCheck"
            >
              全选
            </el-button>
          </div>
          <BKTable
            ref="grid"
            class="flex-1 overflow-hidden"
            :has-seq="false"
            :has-checkbox="false"
            :pager-config="{layouts:['PrevPage','Number','NextPage']}"
            style="padding: 0;"
            :page-size="100"
            @checkbox-change="checkboxChange"
            @checkbox-all="checkboxChange"
            :columns="finalColumns"
            data-url="/grid/getTableData"
            :data-params="mergedDataParams"
            size="mini"
            :before-query="beforeQuery"
            @querySuccess="querySuccess"
            :tooltip-config="{ contentMethod: tooltipContent }"
            border="inner"
            :row-class-name="rowClassName"
          />
        </div>
        <div class="buttons d-flex-c jc-c ai-c">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-arrow-left"
            @click="removeData"
            :disabled="!rightChecked.length"
          />
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-arrow-right"
            @click="addToRight"
            :disabled="!leftChecked.length"
          />
        </div>
        <div class="right-table flex-1 overflow-hidden d-flex-c">
          <div class="title flex-between p-h-mini b-b">
            <span class="d-flex ai-c"><i class="ri-list-check" />{{ titles[1] }}<span class="count m-l-mini">({{ tableData.length }})</span></span>
            <el-button
              type="text"
              style="font-size: 16px;"
              @click="clear"
            >
              清空
            </el-button>
          </div>
          <BKTable
            ref="rightGrid"
            class="flex-1 overflow-hidden"
            :has-seq="false"
            :has-checkbox="false"
            :pager-config="{layouts:['PrevPage','Number','NextPage']}"
            style="padding: 0;"
            :page-size="100"
            @checkbox-change="rightCheckboxChange"
            @checkbox-all="rightCheckboxChange"
            :columns="finalColumns"
            size="mini"
            :data="tableData"
            :tooltip-config="{ contentMethod: tooltipContent }"
            @cell-click="rowClick"
            border="inner"
            :row-class-name="rowClassName"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { sizesList } from '../../utils'
import { mapState } from 'vuex'
export default {
  name: 'Transfer',
  props: {
    titles: {
      type: Array,
      default: () => ([])
    },
    type: {
      type: String,
      default: ''
    },
    metaSet: {
      type: String,
      required: true
    },
    methodCode: {
      type: String,
      default: 'select'
    },
    mainIdKey: {
      type: String,
      required: true
    },
    cityData: {
      type: Array,
      default: () => ([])
    },
    columns: {
      type: Array,
      default: () => ([])
    },
    value: {
      type: Array,
      default: () => ([])
    },
    layerId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      rightChecked: [],
      leftChecked: [],
      tableData: [],
      currentCity: this.value,
      leftTotal: 0,
      keywords: '',
      selectValue: '',
      sizesList: sizesList,
      showText: '1',
      textColor: '#333',
      textFontSize: '12'
    }
  },
  computed: {
    ...mapState('map-making', ['stationTextOption', 'projectTextOption']),
    mergedDataParams () {
      return {
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: this.metaSet,
        methodCode: this.methodCode
      }
    },
    finalColumns () {
      const list = [].concat(this.columns)
      list.unshift({ type: 'checkbox', width: 40 })
      return list
    },
    placeholder () {
      if (this.type) {
        return '请输入站点名称或站点编号'
      } else {
        return this.metaSet === 'ATT_RES_BASE' ? '请输入水库名称或站码' : '请输入名称'
      }
    }
  },
  watch: {
    tableData (v) {
      this.$emit('change', v)
    },
    currentCity (v) {
      this.$emit('input', v)
    },
    value (v) {
      this.currentCity = v
    }
  },
  created () {
    this.$root.$on('updateMapMaking', this.updateMapMaking)
  },
  beforeDestroy () {
    this.$root.$off('updateMapMaking', this.updateMapMaking)
  },
  methods: {
    setTableData (data) {
      this.tableData = data
    },
    search () {
      this.$refs.grid.refresh()
    },
    checkboxChange () {
      const rows = this.$refs.grid.$refs.table.getCheckboxRecords()
      this.leftChecked = rows
    },
    beforeQuery (data) {
      if (this.type) {
        data.methodParams = JSON.stringify({
          SJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 1).map(item => item[0]).join(',') : '',
          XJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 2).map(item => item[1]).join(',') : '',
          ZLMC: this.type,
          NAME: this.keywords,
          SKLX: this.selectValue
        })
      } else {
        data.methodParams = {
          SJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 1).map(item => item[0]).join(',') : '',
          XJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 2).map(item => item[1]).join(',') : '',
          NAME: this.keywords,
          SKLX: this.selectValue
        }
      }
      return data
    },
    async alllLeftCheck () {
      const methodParams = this.type ? {
        SJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 1).map(item => item[0]).join(',') : '',
        XJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 2).map(item => item[1]).join(',') : '',
        ZLMC: this.type,
        NAME: this.keywords,
        SKLX: this.selectValue
      } : {
        SJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 1).map(item => item[0]).join(',') : '',
        XJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 2).map(item => item[1]).join(',') : '',
        NAME: this.keywords,
        SKLX: this.selectValue
      }
      const { rows } = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        metaSet: this.mergedDataParams.metaSet,
        methodCode: this.mergedDataParams.methodCode,
        methodParams
      })
      this.tableData = rows
    },
    rightCheckboxChange () {
      const rows = this.$refs.rightGrid.$refs.table.getCheckboxRecords()
      this.rightChecked = rows
    },
    clear () {
      this.tableData = []
      this.rightChecked = []
    },
    addToRight () {
      const currentIds = this.tableData.map(item => item[this.mainIdKey])
      this.leftChecked.forEach(item => {
        if (!currentIds.includes(item[this.mainIdKey])) {
          this.tableData.push(item)
        }
      })
      this.leftChecked = []
      this.$refs.grid.clearCheckboxRow()
    },
    removeData () {
      this.rightChecked.forEach(item => {
        const i = this.tableData.findIndex(t => t[this.mainIdKey] === item[this.mainIdKey])
        this.tableData.splice(i, 1)
      })
      this.rightChecked = []
    },
    querySuccess ({ data }) {
      this.leftTotal = data.total
    },
    tooltipContent ({ row, column, columnIndex }) {
      if (!row) return ''
      if (columnIndex !== 1) {
        return row[column.property]
      } else {
        return row[column.property] + '\n' + (row.XZQMC || '')
      }
    },
    rowClick ({ row, columnIndex }) {
      if (columnIndex === 0) return
      this.$emit('rowClick', row)
    },
    removeRowById (id) {
      const i = this.tableData.findIndex(t => t[this.mainIdKey] === id)
      this.tableData.splice(i, 1)
    },
    changeTextOption () {
      this.$emit('changeLayerStyle', {
        layerId: this.layerId,
        textOption: {
          fontSize: this.textFontSize,
          color: this.textColor,
          showText: this.showText
        }
      })
      if (this.layerId.startsWith('station-')) {
        this.$store.commit('map-making/setStationTextOption', Object.assign(this.stationTextOption, {
          [this.layerId]: {
            fontSize: this.textFontSize,
            color: this.textColor,
            showText: this.showText
          }
        }))
      } else if (this.layerId.startsWith('gc-')) {
        this.$store.commit('map-making/setProjectTextOption', Object.assign(this.projectTextOption, {
          [this.layerId]: {
            fontSize: this.textFontSize,
            color: this.textColor,
            showText: this.showText
          }
        }))
      }
    },
    updateMapMaking () {
      for (const key in this.stationTextOption) {
        if (Object.hasOwnProperty.call(this.stationTextOption, key)) {
          const element = this.stationTextOption[key]
          if (this.layerId === key) {
            this.showText = element.showText
            this.textColor = element.color
            this.textFontSize = element.fontSize.toString()
            return
          }
        }
      }
      for (const key in this.projectTextOption) {
        if (Object.hasOwnProperty.call(this.projectTextOption, key)) {
          const element = this.projectTextOption[key]
          if (this.layerId === key) {
            this.showText = element.showText
            this.textColor = element.color
            this.textFontSize = element.fontSize.toString()
            return
          }
        }
      }
    },
    rowClassName ({ row }) {
      if (row.KJDX || (row.LGTD && row.LTTD)) {
        return ''
      } else {
        if (['gc-3', 'gc-6', 'gc-7', 'gc-8'].includes(this.layerId)) {
          return ''
        }
        return 'c-red'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.transfer-container {
  .left-table,
  .right-table {
    height: 100%;
    background: #fff;
    border: 1px solid #e1e9f0;
    padding: 0;
    border-radius: 8px;

    .title {
      > span > i {
        font-size: 22px;
        line-height: 22px;
        color: #0080ff;
        margin-right: 4px;
      }

      .count {
        font-size: 12px;
        font-weight: bold;
        color: #999;
      }
    }
  }

  .buttons {
    padding: 0 12px;
    gap: 25px;

    > .el-button {
      margin: 0;
      border-radius: 8px;
      padding: 7px 12px;

      > i {
        font-size: 20px;
      }
    }
  }
}
</style>
